import { authMiddleware } from '@/lib/api';
import { clientQueryUserDetails, queryPath } from '@/services/api';
import { cookies } from 'next/headers';
import UserIdPage from '@/app/[locale]/users/[id]/userid';
import ResetPage from '@/app/[locale]/reset/reset';
import type { Metadata as MetadataNext } from 'next';
import type { IPath, IUserClientDetails } from '@/interfaces';
import {
  createError,
  filterNumericParams,
  getMetadata,
  isNum,
} from '@/lib/tool';
import { notFound } from 'next/navigation';
import { getTranslator } from 'next-intl/server';
import { getTranslatedFields } from '@/lib/dictionaries';

async function getData(
  id: string,
  searchParams: {
    sectionId?: string;
    tagId?: string;
  },
) {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = clientQueryUserDetails({
      baseURL: process.env.APP_API_SERVER,
      token,
      id,
      query: searchParams,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    return {
      isSuccess: true,
      isError: false,
      data: {
        path: resp1.data as IPath,
        userDetails: resp2.data as IUserClientDetails,
        queryParams: searchParams,
      },
    };
  } catch (e: any) {
    return {
      isSuccess: false,
      isError: true,
      error: e,
    };
  }
}

export async function generateMetadata({
  params: { id, locale },
  searchParams: { sectionId, sid, tagId, tid, v },
}: {
  params: { id?: string; locale: string };
  searchParams: {
    sectionId?: string;
    sid?: string;
    tagId?: string;
    tid?: string;
    v?: 'h5';
  };
}): Promise<MetadataNext> {
  if (!id || !isNum(id)) {
    notFound();
  }

  const t = await getTranslator(locale);
  const data = await getData(
    id,
    filterNumericParams({
      sectionId: sectionId ?? sid,
      tagId: tagId ?? tid,
    }),
  );
  if (data.isError) {
    return getMetadata({ title: t('userIdPage.userHomepage') });
  }

  const user = data.data!.userDetails.user;
  return getMetadata({
    title: user.alias,
    authors: {
      url: `/users/${user.id}`,
      name: user.alias,
    },
    creator: `${user.alias} (ID. ${user.id})`,
    description: `${user.alias} - ${t('userIdPage.personalHomepage')}`,
  });
}

export default async function Page({
  params: { id, locale },
  searchParams: { sectionId, sid, tagId, tid, v },
}: {
  params: { id?: string; locale: string };
  searchParams: {
    sectionId?: string;
    sid?: string;
    tagId?: string;
    tid?: string;
    v?: 'h5';
  };
}) {
  if (!id || !isNum(id)) {
    notFound();
  }

  const data = await getData(
    id,
    filterNumericParams({
      sectionId: sectionId ?? sid,
      tagId: tagId ?? tid,
    }),
  );
  if (data.isError) {
    return <ResetPage error={createError(data.error)} />;
  }

  const source = data.data!;
  const translatedFields = await getTranslatedFields(locale, 'userIdPage');

  return <UserIdPage source={source} translatedFields={translatedFields} />;
}
